class Solution(object):
    def integerReplacement(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n > 3:
            if n % 2 == 0:
                n = n // 2
            else:
                if (n - 1) & (1 - n) >= (n + 1) & (- n - 1):
                    n = n - 1
                else:
                    n = n + 1
            count += 1
        if n == 3:
            return count + 2
        if n == 2:
            return count + 1
        if n == 1:
            return 0
